package com.bbva.itradecomex.converter;

import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import org.apache.log4j.Logger;
import org.springframework.web.jsf.FacesContextUtils;

import com.bbva.itradecomex.bo.iface.ConsultaComunBO;
import com.bbva.itradecomex.bo.impl.ConsultaComunBOImpl;
import com.bbva.itradecomex.domain.Moneda;

@FacesConverter(value="monedaConverter")
public class MonedaConverter implements Converter{
	
	private static final Logger log = Logger.getLogger(MonedaConverter.class);

	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String submittedValue)
			throws ConverterException {
		ConsultaComunBO consultaComunBO = (ConsultaComunBOImpl)FacesContextUtils.getWebApplicationContext(arg0)
											.getBean("consultaComunBOImpl");
		List<Moneda> listMoneda = null;
		try {
			listMoneda = consultaComunBO.getListBusquedaMoneda(submittedValue.trim());
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(),e);
		}
		
		Moneda moneda = null;
		
		if(listMoneda != null && listMoneda.size() > 0){
			moneda = listMoneda.get(0);
		}
		
		return moneda;
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object value)
			throws ConverterException {
		Moneda moneda = new Moneda();
		moneda = (Moneda) value;
		return moneda.getDescripcion();
	}

}
